package com.itcast.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping
public class SendMessageController {
    @Autowired
    private RabbitTemplate rabbitTemplate;


    @GetMapping("/sendDirectMessage")
    public String sendMessage() {
        String messageId = String.valueOf(UUID.randomUUID());
        String messageData = "test message, hello!";
        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Map<String,Object> map=new HashMap<>();
        map.put("messageId",messageId);
        map.put("messageData",messageData);
        map.put("createTime",createTime);
        //将消息携带绑定键值：TestDirectRouting 发送到交换机TestDirectExchange
        CorrelationData correlationData = new CorrelationData();
        correlationData.getFuture().addCallback(result ->{
            if(result.isAck()) {
                log.info("消息投递成功：" + correlationData.getId());
            } else {
                log.info("消息投递失败：" + result.getReason());
            }
        }, ex -> {
                log.info("消息发送异常：" + ex.getMessage());
        });
        rabbitTemplate.convertAndSend("direct.Exchange", "directRoutingkey", map,correlationData);
        return "ok";

    }
    @GetMapping("/topic")
    public void sendMessageTopic(String msg) {

        rabbitTemplate.convertAndSend("topic.exchange","china.news",msg);
    }
    @GetMapping("/direct")
    public void sendMesssageDirect(String msg,String routingKey) {
        rabbitTemplate.convertAndSend("direct.exchange1",routingKey,msg);
    }
    @GetMapping("/dead")
    public void sendMessageDead(String msg){
        CorrelationData correlationData = new CorrelationData();
        correlationData.getFuture().addCallback(result ->{
            if(result.isAck()) {
                log.info("消息投递成功：" + correlationData.getId());
            } else {
                log.info("消息投递失败：" + result.getReason());
            }
        }, ex -> {
            log.info("消息发送异常：" + ex.getMessage());
        });
        rabbitTemplate.convertAndSend("directExchange","direct",msg,correlationData);
    }
    @PostMapping("/fanout")
    public void sendMessageFanout(String msg) {
        rabbitTemplate.convertAndSend("fanoutExchange","",msg);

    }
}
